package com.example.zwlyz.views;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.zwlyz.R;
import com.example.zwlyz.bean.User;
import com.example.zwlyz.database.DBHelper;
import com.example.zwlyz.utils.SpUtils;

public class Register extends AppCompatActivity implements View.OnClickListener{
    private EditText register_name_et;
    private EditText register_password_et;
    private Button register_bt;
    private SpUtils mSpUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        register_name_et = findViewById(R.id.etUsername);
        register_password_et = findViewById(R.id.etPassword);
        register_bt = findViewById(R.id.btnRegister);
        register_bt.setOnClickListener(this);
        mSpUtils = new SpUtils(this);
    }

    @Override
    public void onClick(View v) {//注册按钮点击事件
        String name = register_name_et.getText().toString();
        String password = register_password_et.getText().toString();

        //判断输入的内容都不能是空
        if (allInputNotEmpty(name,password)) {
            User user = new User();
            user.setUsername(name);
            user.setPassword(password);
            //将新注册的学生信息保存到数据库
            int id = (int) DBHelper.getInstance(this).insertUser2(user);
            //记录当前登录账号的id
            mSpUtils.putInt(SpUtils.LOGIN_KEY, id);
            System.out.println("新注册的学生id："+id);

            //注册成功，数据保存后，在这里跳转到主界面
            Intent intent = new Intent(Register.this, Login.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            Toast.makeText(this, "输入不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean allInputNotEmpty(String... inputStrings) {
        for (int i = 0; i < inputStrings.length; i++) {
            if (TextUtils.isEmpty(inputStrings[i])) {
                return false;
            }
        }
        return true;
    }

}
